package main

import (
	"log"
	"qcoder_reader/config"
	"qcoder_reader/handlers"
	"qcoder_reader/middleware"
	"qcoder_reader/utils"

	"github.com/gin-gonic/gin"
)

func main() {
	// 加载配置
	config.LoadConfig()

	// 初始化Consul连接
	err := utils.InitConsul()
	if err != nil {
		log.Fatalf("Failed to initialize Consul: %v", err)
	}

	// 创建Gin引擎
	r := gin.Default()

	// 静态文件服务
	r.Static("/static", "./static")
	// 默认页面
	r.GET("/", func(c *gin.Context) {
		c.Redirect(302, "/static/index.html")
	})

	// 登录路由
	r.POST("/api/login", handlers.Login)

	// 受保护的路由组
	protected := r.Group("/api")
	protected.Use(middleware.AuthMiddleware())
	{
		protected.GET("/services", handlers.GetServices)
		protected.GET("/services/:name/instances", handlers.GetServiceInstances)
		protected.POST("/services", handlers.AddService)
		protected.DELETE("/services/:id", handlers.DeleteService)
		protected.GET("/config/consul", handlers.GetConsulConfig)
		protected.POST("/config/consul", handlers.UpdateConsulConfig)
	}

	// 启动服务器
	err = r.Run(":9876")
	if err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
